<template>
  <van-form @submit="onSubmit" label-width="1.2rem">
    <div class="mt-1">
      <van-nav-bar
        title="发布"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
      >
        <template #right>
          <div class="xl:w-12 w-9">
            <van-button
              :loading="btnLoading"
              loading-text="发布中..."
              round
              block
              type="primary"
              native-type="submit"
              size="small"
            >
              发布
            </van-button>
          </div>
        </template>
      </van-nav-bar>

      <van-cell-group inset>
        <van-field
          label-width="1.2rem"
          v-model="form.title"
          name="标题"
          label="标题"
          placeholder="标题"
          :rules="[{ required: true, message: '请填写标题' }]"
        />
      </van-cell-group>
      <van-cell-group inset v-if="isMobileTerminal">
        <van-field
          rows="2"
          label-width="1.2rem"
          autosize
          show-word-limit
          v-model="form.content"
          name="内容"
          label="内容"
          placeholder="内容"
          type="textarea"
        />
      </van-cell-group>
      <van-cell-group inset>
        <van-field name="checkboxGroup" label="标签" label-width="1.2rem">
          <template #input>
            <van-checkbox-group v-model="form.tags" direction="horizontal">
              <van-checkbox
                class="mb-1"
                v-for="(item, index) in tagList"
                :key="index"
                :name="item.label"
                shape="square"
                >{{ item.label }}</van-checkbox
              >
              <div>
                <van-button
                  @click="navToTgas"
                  round
                  block
                  size="mini"
                  type="primary"
                >
                  标签管理
                </van-button>
              </div>
            </van-checkbox-group>
          </template>
        </van-field>
        <van-field name="图片" label="图片" label-width="1.2rem">
          <template #input>
            <van-uploader
              multiple
              :max-count="10"
              v-model="fileList"
              :after-read="afterRead"
              @delete="deleteImg"
              :preview-options="{
                closeable: true,
              }"
            />
          </template>
        </van-field>
      </van-cell-group>
      <div class="pl-1 pr-1">
        <VMdEditor
          :height="'400px'"
          v-model="valueHtml"
          v-if="!isMobileTerminal"
        ></VMdEditor>
      </div>
      <!-- <div style="margin: 16px">
        <van-button
          :loading="btnLoading"
          loading-text="发布中..."
          round
          block
          type="primary"
          native-type="submit"
        >
          提交
        </van-button>
      </div> -->
    </div>
  </van-form>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { Toast } from "vant";
import "vant/es/toast/style";
import router from "@/router";
import { uploadfiles } from "@/api/login.js";
import { postPosts, editPosts } from "@/api/posts.js";
import { isMobileTerminal } from "@/utils/flexible";
import { getPostsDetails } from "@/api/posts.js";
import { getTags } from "@/api/tags.js";
import VMdEditor from "@/components/VMdEditor.vue";
// import VueMarkdownEditor, { xss } from "@kangc/v-md-editor";
const fileList = ref([]);
const form = ref({
  title: "",
  content: "",
  tags: [],
  imgs: "",
});
console.log("fileList :>> ", isMobileTerminal);
const tagList = ref([]);
const valueHtml = ref("");
const getPostsDetailItem = () => {
  getPostsDetails({ id: id }).then((res) => {
    res.tags = res.tags.split(",");
    form.value = res;
    valueHtml.value = res.content;
    if (res.imgs) {
      fileList.value = res.imgs.split(",").map((item) => {
        return {
          url: item,
        };
      });
    }
  });
};
const id = router.currentRoute.value.query.id;
onMounted(() => {
  if (id) {
    getPostsDetailItem();
  }
});

const btnLoading = ref(false);
const onClickLeft = () => router.push("/");
const navToTgas = () => {
  router.push({
    path: "/myTags",
  });
};
const deleteImg = (file) => {};
const afterRead = (file) => {};
const editSubmit = async () => {
  const res1 = fileList.value.filter((item) => !item.url);
  const res2 = fileList.value.filter((item) => item.url);
  let imsgs = [];
  // 有文件上传
  if (res1.length) {
    const imsg = await asyncUploadfiles(res1);
    imsgs = imsg.split(",");
  }
  if (res2.length) {
    const img = res2.map((item) => item.url);
    imsgs = imsgs.concat(img);
  }
  btnLoading.value = true;
  try {
    await editPosts({
      id: id,
      imgs: imsgs.join(","),
      tags: form.value.tags.join(","),
      title: form.value.title,
      content: isMobileTerminal.value ? form.value.content : valueHtml.value,
    });
    btnLoading.value = false;
    Toast.success("编辑成功");
    setTimeout(() => {
      router.push("/home");
    }, 1000);
    getPostsDetailItem();
  } catch (error) {
    btnLoading.value = false;
  }
};
const onSubmit = (values) => {
  if (id) {
    editSubmit();
  } else {
    add();
  }
};
const asyncUploadfiles = async (fileList) => {
  return new Promise(async (resolve, reject) => {
    const formData = new FormData();
    fileList.forEach((item) => {
      formData.append("file", item.file);
    });
    try {
      const resImg = await uploadfiles(formData);
      const { url } = resImg;
      // form.value.imgs = url;
      resolve(url);
    } catch (error) {
      // btnLoading.value = false;
      reject(error);
    }
  });
};
const add = async () => {
  btnLoading.value = true;
  if (fileList.value.length) {
    const formData = new FormData();
    fileList.value.forEach((item) => {
      formData.append("file", item.file);
    });
    try {
      const resImg = await uploadfiles(formData);
      const { url } = resImg;
      form.value.imgs = url;
    } catch (error) {
      btnLoading.value = false;
    }
  }
  try {
    // const html = xss.process(
    //   VueMarkdownEditor.vMdParser.themeConfig.markdownParser.render(
    //     valueHtml.value
    //   )
    // );
    await postPosts({
      ...form.value,
      tags: form.value.tags.join(","),
      content: isMobileTerminal.value ? form.value.content : valueHtml.value,
    });
    btnLoading.value = false;
    Toast.success("发布成功");
    setTimeout(() => {
      router.push("/home");
    }, 1000);
  } catch (error) {
    btnLoading.value = false;
  }
};

const getTagsList = () => {
  getTags().then((res) => {
    tagList.value = res;
  });
};
getTagsList();
</script>

<style lang="scss" scoped>
</style>